
def eval_import(s):
    if (':' not in s):
        return simple_import(s)
    else:
        (module_name, expr,) = s.split(':', 1)
        module = import_module(module_name)
        obj = eval(expr, module.__dict__)
        return obj



def simple_import(s):
    parts = s.split('.')
    module = import_module(parts[0])
    name = parts[0]
    parts = parts[1:]
    last_import_error = None
    while parts:
        name += ('.' + parts[0])
        try:
            module = import_module(name)
            parts = parts[1:]
        except ImportError, e:
            last_import_error = e
            break

    obj = module
    while parts:
        try:
            obj = getattr(module, parts[0])
        except AttributeError:
            raise ImportError(('Cannot find %s in module %r (stopped importing modules with error %s)' % (parts[0],
             module,
             last_import_error)))
        parts = parts[1:]

    return obj



def import_module(s):
    mod = __import__(s)
    parts = s.split('.')
    for part in parts[1:]:
        mod = getattr(mod, part)

    return mod



def try_import_module(module_name):
    try:
        return import_module(module_name)
    except ImportError, e:
        if not getattr(e, 'args', None):
            raise 
        desc = e.args[0]
        if not desc.startswith('No module named '):
            raise 
        desc = desc[len('No module named '):]
        parts = module_name.split('.')
        for i in range(len(parts)):
            if (desc == '.'.join(parts[i:])):
                return 

        raise 



